package own.application.global.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TcpByteUtil {

	public static void printHexString(byte[] b) {
		System.out.print("服务器-》响应/反馈-》客户端：");
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			System.out.print(hex.toUpperCase()+ " ");
		}
		System.out.println();
	}
	
	/**
	 * 此方法仅供参考
	 * 转义 byte 数组 【根据规则 内容自行调整】 
	 * @param bytes 已转义内容
	 * @param size 已转义长度
	 * @return
	 */
	public static byte[] escape(byte[] bytes,int size) {
		
		//总长度
		int newSize = size+2;
		
		/**
		 * 此处规则为 7E（126） 要转义成 7D（125） 02
		 * 		  7D 要 转义成 7D 01
		 * 转义后 的长度 会 大于 转义前	
		 * 用于获取转义前 长度
		 */
		for (int i = 1; i < size+2; i++) {
			//根据规则 裁剪长度， 此处规则为 遇到 16进制7E（125） 
			if(bytes[i] == 125){
				newSize -= 1;
			}
		}
		//创建一个 新的报文空间
		byte[] escapeBytes = new byte[newSize];
		
		// 开始还原转义前报文
		for (int i = 0,j = 0; i < size+2; i++ , j++) {
			
			if(bytes[i] == 125){
				if(bytes[i + 1] == 1){
					escapeBytes[j] = 125;
				}else{
					escapeBytes[j] = 126;
				}
				i+=1;
			}else{
				escapeBytes[j] = bytes[i];
			}
		}

		return escapeBytes;
	}
	
	/**
	 * byte 数组 转 16进制字符串
	 * @param bytes 转换数据
	 * @param offset 转换起始索引
	 * @param length 需要转换的长度
	 * @return
	 */
	public static String bytesHexString(byte[] bytes,int offset,int length) {
		StringBuilder hexs = new StringBuilder();
		int end = offset + length;
		for (int i = offset; i < end; i++) {
			String hex = Integer.toHexString(bytes[ i ] & 0xFF);
			if (hex.length() == 1) {   
				hex = '0' + hex;   
			}  
			hexs.append(hex.toUpperCase()+"");  
		}
		return hexs.toString();
	}

	/**
	 * 转换 16 进制 字符串为 byte 数组
	 * @param hexString 16进制字符串
	 * @return
	 */
	public static byte[] hexToBytes(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		char[] hexChars = hexString.toCharArray();
		int length = hexString.length() / 2;
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/**
	 * int转hex
	 * @param value	值
	 * @param byteCount 转换成n个字节的hex【不足补0，溢出无操作】
	 * @param order 排序 1.正序【大端】，2.反序【小端】
	 * @return
	 */
	public static String integerToHexString(Integer value,Integer byteCount,Integer order) {
		StringBuilder sb = new StringBuilder();
		String tmp = null;
		// 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
		while (value != 0) {
			tmp = Integer.toHexString(0xFF & value);
			if (tmp.length() == 1)// 每个字节8为，转为16进制标志，2个16进制位
			{
				tmp = "0" + tmp;
			}
			if(order == 1){
				sb.insert(0, tmp.toUpperCase());
			}else{
				sb.append(tmp.toUpperCase());
			}
			value = value >>> 8;
		}
		int endLen = byteCount - (sb.length()/2);
		for(int i = 0; i < endLen; i++){
			if(order == 1){
				sb.insert(0, "00");
			}else{
				sb.append("00");
			}
		}
		return sb.toString();
	}
	
	/**
	 * int转hex
	 * @param value	值
	 * @param order 排序 1.正序【大端】，2.反序【小端】
	 * @return
	 */
	public static String integerToHexString(Integer value,Integer order) {
		return integerToHexString(value,0,order);
	}
	
	/**
	 * byte 数组转 Integer
	 * @param bytes 转换数据
	 * @param offset 起始索引
	 * @param len 数据长度
	 * @return
	 */
	public static Integer byteToInteger(byte [] bytes,int offset,int len) {
		Integer value = 0;
		if(len == 2){
			value =  bytes[offset] & 0xFF |  
	                (bytes[offset+1] & 0xFF) << 8;
		}else{
			value =  bytes[offset] & 0xFF |  
	                (bytes[offset+1] & 0xFF) << 8 |  
	                (bytes[offset+2] & 0xFF) << 16 |  
	                (bytes[offset+3] & 0xFF) << 24;
		}
         
        return value;
    }
	
	/**  
     * int整数转换为4字节的byte数组  
     *   
     * @param i  整数  
     * @return byte数组  
     */    
    public static byte[] intToByte4(int i) {    
        byte[] targets = new byte[4];    
        targets[3] = (byte) (i & 0xFF);    
        targets[2] = (byte) (i >> 8 & 0xFF);    
        targets[1] = (byte) (i >> 16 & 0xFF);    
        targets[0] = (byte) (i >> 24 & 0xFF);    
        return targets;    
    }  
	
	public static Integer hexStringToInt(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		Integer value = 0;
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			value += (int) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return value;
	}
	
	public static byte BCCCheck(byte [] bytes,int offset,int len){
		byte temp = bytes[offset];  
		int end = offset + len;
	    for (int i = 1; i < end; i++) {  
	        temp ^= bytes[i];  
	    }  
	  
	    return temp; 
	}
	
	public static byte checkSum(byte [] bytes,int offset,int len){
		byte temp = 0;  
		int end = offset + len;
	    for (int i = 1; i < end; i++) {  
	        temp += bytes[i];  
	    }  
	  
	    return temp; 
	}
	
	public static void main(String[] args) {
		System.out.println(TcpByteUtil.integerToHexString(28,4,2));
	}
}
